package com.lichongbing.lyoggl.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.google.common.cache.Cache;
import com.lichongbing.lyoggl.apple.ApnsServe;
import com.lichongbing.lyoggl.mapper.TimeEntriesMapper;
import com.lichongbing.lyoggl.model.*;
import com.lichongbing.lyoggl.service.*;
import com.lichongbing.lyoggl.utils.DateUtils;
import com.lichongbing.lyoggl.utils.JwtTokenUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.*;


/**
 * @author lichongbing
 * @version 1.0.0
 * @createdate 2021/12/5 10:20 上午
 * @description: TODO
 */
@Slf4j
@RestController
@RequestMapping("/timeEntries")
public class TimeEntriesController {


    @Autowired
    private Cache<String, String> cache;

    @Autowired
    private TimeEntriesMapper timeEntriesMapper;
    @Autowired
    private LyogglUsersService lyogglUsersService;

    @Autowired
    private ApnsServe apnsServe;

    @Autowired
    private FlagsService flagsService;

    @Autowired
    private VflagsService vflagsService;

    @Autowired
    private TagsService tagsService;

    @Autowired
    private ProjectService projectService;

    /**
     * 新增或编辑
     */

    @PostMapping("/save")
    public Object save(@RequestBody JSONArray timeEntries) {
        return null;
    }

    /**
     * 删除
     */
    @PostMapping("/delete")
    public Object delete(int id) {
        TimeEntries timeEntries = timeEntriesMapper.selectOne(new QueryWrapper<TimeEntries>().eq("timeEntries_id", id));
        return null;
    }

    /**
     * 查询
     */
    @PostMapping("/find")
    public Object find(int id) {
        TimeEntries timeEntries = timeEntriesMapper.selectOne(new QueryWrapper<TimeEntries>().eq("timeEntries_id", id));
        return null;
    }

    /**
     * 自动分页查询
     */
    @PostMapping("/list")
    public Object list(String searchParams,
                       @RequestParam(required = false, defaultValue = "0") int page,
                       @RequestParam(required = false, defaultValue = "10") int limit) {
        return null;
    }

    @GetMapping("/list")
    public ModelAndView listPage() {
        return new ModelAndView("timeEntries-list");
    }

    @GetMapping("/edit")
    public ModelAndView editPage(int id) {
        TimeEntries timeEntries = timeEntriesMapper.selectOne(new QueryWrapper<TimeEntries>().eq("timeEntries_id", id));
        return new ModelAndView("timeEntries-edit", "timeEntries", timeEntries);
    }

    /**
     * 新增记录
     * @param jsonObject
     * @param request
     * @return
     */
    @PostMapping("/add")
    public String addTimeEntrie(@RequestBody JSONObject jsonObject, HttpServletRequest request) {
        String token = request.getHeader("token");
        boolean expiration = JwtTokenUtils.isExpiration(token);
        TimeEntries timeEntries = new TimeEntries();

        String id = UUID.randomUUID().toString().replace("-", "");
        if (expiration == false) {
            String userid = JwtTokenUtils.getUserid(token);
            String oldstart = cache.getIfPresent(userid);
            String timeEntrieid = cache.getIfPresent(userid+"timeEntrieid");
            String fidolod = cache.getIfPresent(userid+"fid");
            String start = null;
            String start1 = jsonObject.getString("start");
            if (start1.contains("年")) {
                start = DateUtils.getStringToDate(start1);
            } else if(start1.contains("Mon")||start1.contains("Tue")||start1.contains("Wed")||start1.contains("Thu")||start1.contains("Fri")||start1.contains("Sat")||start1.contains("Sun")){
                start = DateUtils.getDateStEnlishToLocal(start1);
            } else {
                start = start1;
            }
            String descriptions = jsonObject.getString("descriptions");
            String tid = jsonObject.getString("tid");
            String fid = jsonObject.getString("fid");
            String pid = jsonObject.getString("pid");
            if (timeEntrieid != null && oldstart != null && fidolod !=null) {
                long duration = DateUtils.getDuration(oldstart, start);
                timeEntriesMapper.updateDurationById(start, duration, timeEntrieid);
                UpdateWrapper<Flags> updateWrapper = new UpdateWrapper<>();
                updateWrapper.eq("id",fidolod).eq("uid",userid).set("start","1");
                flagsService.update(null,updateWrapper);
            }
            UpdateWrapper<Flags> updateWrapper = new UpdateWrapper<>();
            updateWrapper.eq("id",fid).eq("uid",userid).set("start","0");
            flagsService.update(null,updateWrapper);
            cache.put(userid+"timeEntrieid", id);
            cache.put(userid+"fid", fid);
            cache.put(userid, start);
            timeEntries.setUid(userid);
            timeEntries.setId(id);
            timeEntries.setStart(start);
            timeEntries.setPid(pid);
            timeEntries.setDescription(descriptions);
            timeEntries.setTid(tid);
            timeEntries.setFid(fid);
            timeEntriesMapper.insert(timeEntries);
            String flagName = getProjectNamebypid(pid);
            Tags tags = getTagsProjectNamebypid(tid);
            List<Vflags> vflag = vflagsService.getByPid(fid);
            pushNotifications(userid,flagName,start,vflag,tags);
            return "添加成功";
        } else {

            return "token无效";
        }
    }

    /**
     * 新增便捷记录
     * @param jsonObject
     * @param request
     * @return
     */
    @PostMapping("/startTimer")
    public String createTimer(@RequestBody JSONObject jsonObject, HttpServletRequest request){
        String token = request.getHeader("token");
        boolean expiration = JwtTokenUtils.isExpiration(token);
        TimeEntries timeEntries = new TimeEntries();
        String id = UUID.randomUUID().toString().replace("-", "");
        if (expiration == false) {
            String userid = JwtTokenUtils.getUserid(token);
            String fidolod = cache.getIfPresent(userid+"fid");
            String timeEntrieid = cache.getIfPresent(userid+"timeEntrieid");
            String oldstart = cache.getIfPresent(userid);
            String pid = jsonObject.getString("id");
            Date date = new Date();
            SimpleDateFormat dateFormat= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String start = dateFormat.format(date);
            if (timeEntrieid != null && oldstart != null ) {
                long duration = DateUtils.getDuration(oldstart, start);
                timeEntriesMapper.updateDurationById(start, duration, timeEntrieid);
            }
            UpdateWrapper<Flags> updateWrapper = new UpdateWrapper<>();
            updateWrapper.eq("id",pid).eq("uid",userid).set("start","0").set("startid",id);
            flagsService.update(null,updateWrapper);
            // 上条停止记录更新状态
            UpdateWrapper<Flags> updateWrapper1 = new UpdateWrapper<>();
            if(fidolod !=null){
                updateWrapper1.eq("id",fidolod).eq("uid",userid).set("start","1");
                flagsService.update(null,updateWrapper1);
            }
            String flagName = jsonObject.getString("title");
            cache.put(userid+"timeEntrieid", id);
            cache.put(userid+"pid", pid);
            cache.put(userid, start);
            timeEntries.setUid(userid);
            timeEntries.setId(id);
            timeEntries.setStart(start);
            timeEntries.setPid(pid);
            timeEntries.setTid(pid);
            timeEntries.setFid(pid);
            timeEntriesMapper.insert(timeEntries);
            Tags tags = getTagsProjectNamebypid(pid);
            List<Vflags> vflag = vflagsService.getByPid(pid);
            pushNotifications(userid,flagName,start,vflag,tags);
            return "添加成功";
        }else {
            return "token无效";
        }

    }

    /**
     * 停止时间记录
     * @param request
     * @return
     */
    @PostMapping("/stopTimer")
    public String stopTimer(HttpServletRequest request){
        String token = request.getHeader("token");
        boolean expiration = JwtTokenUtils.isExpiration(token);
        if (expiration == false) {
            String userid = JwtTokenUtils.getUserid(token);
            String timeEntrieid = cache.getIfPresent(userid+"timeEntrieid");
            String oldstart = cache.getIfPresent(userid);
            String fidolod = cache.getIfPresent(userid+"fid");
            Date date = new Date();
            SimpleDateFormat dateFormat= new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
            String start = dateFormat.format(date);
            UpdateWrapper<Flags> updateWrapper1 = new UpdateWrapper<>();
            if (timeEntrieid != null && oldstart != null && fidolod !=null) {
                long duration = DateUtils.getDuration(oldstart, start);
                timeEntriesMapper.updateDurationById(start, duration, timeEntrieid);
                updateWrapper1.eq("id",fidolod).eq("uid",userid).set("start","1");
                flagsService.update(null,updateWrapper1);
                return "ok";
            }
            return "null";
        }
        return "token 无效";

    }


    private String getProjectNamebypid(String pid) {
       return projectService.getProjectNamebypid(pid);
    }

    private Tags getTagsProjectNamebypid(String tid) {
        return tagsService.getById(tid);
    }

    /**
     *
     * @param userid
     * @param timentity
     * @param start
     * @param vflags
     * @param tags
     */
    private void pushNotifications(String userid, String timentity, String start, List<Vflags> vflags, Tags tags){
        //灵动岛和锁屏组件状态消息更新
        long timestamp = System.currentTimeMillis()/1000L;
        JSONObject payloadjson = new JSONObject();
        JSONObject aps = new JSONObject();
        aps.put("timestamp", timestamp);
        aps.put("event", "update");
        aps.put("displayname", vflags.get(0).getName());
        aps.put("id",  vflags.get(0).getId());
        Double r = Double.valueOf(vflags.get(0).getR());
        Double g = Double.valueOf(vflags.get(0).getG());
        Double b = Double.valueOf(vflags.get(0).getB());
        aps.put("name",  vflags.get(0).getName());
        aps.put("r", r);
        aps.put("g", g);
        aps.put("b", b);
        aps.put("color", vflags.get(0).getColor());
        aps.put("usetime", vflags.get(0).getUsetime());
        JSONObject contentState = new JSONObject();
        contentState.put("name",timentity);
        contentState.put("time",start);
        contentState.put("tag",tags.getName());
        Double r1 = Double.valueOf(tags.getR());
        Double g1 = Double.valueOf(tags.getG());
        Double b1 = Double.valueOf(tags.getB());
        contentState.put("r",r1);
        contentState.put("g",g1);
        contentState.put("b",b1);
        contentState.put("plan",vflags.get(0).getEstimatedSeconds());
        double v = vflags.get(0).getUsetime() / vflags.get(0).getEstimatedSeconds();
        contentState.put("process",v);
        aps.put("content-state", contentState);
        payloadjson.put("aps", aps);
        String payload = JSON.toJSONString(payloadjson);
        System.out.println(payload);
        apnsServe.updateLockScreenandDynamicIsland(userid,payload);
    }


    @PostMapping("/token")
    public void verytoken() {
        String token = "eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiIwMDA1NTEuMDY2Yzk1N2M0OWUxNGExYWFjNmFmM2FlNjJiM2E3NzkuMDkxOCIsImlzcyI6ImxpY2hvbmdiaW5nIiwiZXhwIjoxNjQ4ODI0MTE4LCJ1c2VyaWQiOiIwMDA1NTEuMDY2Yzk1N2M0OWUxNGExYWFjNmFmM2FlNjJiM2E3NzkuMDkxOCIsImlhdCI6MTY0ODgyMTUyNn0.xotko3XCP2F5eOMi0Oz3Z5sF1oX2f6bbJNzh1VxNBjpBJaEOzK8J4ztsliXFn59lE3HZEKyHumPV3sdNQ9doyg";
        boolean expiration = JwtTokenUtils.isExpiration(token);
        TimeEntries timeEntries = new TimeEntries();
    }

    /**
     * 查询从昨天晚上到现在的所有记录
     * @param request
     * @return
     */
    @PostMapping("/today")
    public Object findAllByUidAndTime(HttpServletRequest request) {
        String start = DateUtils.getStartTime();
        String end = DateUtils.getEndTime();
        String token = request.getHeader("token");
        boolean expiration = JwtTokenUtils.isExpiration(token);
        if (expiration == false) {
            String userid = JwtTokenUtils.getUserid(token);
            List<TimeEntries> timeEntries = timeEntriesMapper.getTodayTimeEntries(userid, start, end);
            return timeEntries;
        } else {
            return "token无效";
        }
    }


    /**
     * 查询从上周日到这周六的所有记录
     * @param request
     * @return
     */
    @PostMapping("/toweek")
    public JSONObject getOneWeek(HttpServletRequest request) {
        String start = null;
        String end = null;
        String token = request.getHeader("token");
        boolean expiration = JwtTokenUtils.isExpiration(token);
        List<List<TimeEntries>> timeEntriess = new ArrayList<>();
        JSONObject jsonObject = new JSONObject();
        if (expiration == false) {
            String userid = JwtTokenUtils.getUserid(token);
            boolean flag = lyogglUsersService.isToken(userid);
            if(flag) {
            start = DateUtils.getLastWeekSunday();
            for (int i = 0; i < 7; i++) {
                end = DateUtils.getNextDayEndDate(start);
                List<TimeEntries> timeEntries = timeEntriesMapper.getTodayTimeEntries(userid, start, end);
                start = DateUtils.getNextDayEndDate(start);
                timeEntriess.add(timeEntries);
            }
            jsonObject.put("data", timeEntriess);
            jsonObject.put("code", 200);
            jsonObject.put("msg", "查询成功");
            return jsonObject;}else {
                jsonObject.put("code",402);
                jsonObject.put("msg","token无效");
                return jsonObject;
            }
        } else {
            jsonObject.put("code", 400);
            jsonObject.put("msg", "token无效");
            return jsonObject;
        }
    }

    /**
     * 获取配置
     * @return
     */
    @PostMapping ("/isOpen")
    public int getConfiguration(){
        int i = lyogglUsersService.getConfiguration();
       return i;
    }
}
